package com.esfak47.mediafetcher.app.event;

import com.esfak47.mediafetcher.core.event.Event;
import com.esfak47.mediafetcher.core.event.EventGroupEnum;
import com.esfak47.mediafetcher.core.event.EventHandler;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.eventbus.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @author tony
 * @date 2018/5/21
 */
public class EventBusListenerDelegate {

    private Logger logger = LoggerFactory.getLogger(EventBusListenerDelegate.class);
    private final Multimap<EventGroupEnum, EventHandler> handlers;

    public EventBusListenerDelegate(Set<EventHandler> eventHandlers) {
        handlers = HashMultimap.create();
        for (EventHandler eventHandler : eventHandlers) {
            if (eventHandler.getSupportGroup() != null) {
                eventHandler.getSupportGroup()
                    .forEach(eventGroupEnum -> handlers.put(eventGroupEnum, eventHandler));
            }
        }
    }

    @Subscribe
    public void sub(Event event) {
        logger.info("event {} received",event);
        handlers.get(event.getGroup()).forEach(e -> e.onEvent(event));
    }
}
